package com.pan.hisystem.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.pan.hisystem.pojo.Outpatients;
import com.pan.hisystem.pojo.Registration;
import com.pan.hisystem.mapper.RegistrationMapper;
import com.pan.hisystem.pojo.RespBean;
import com.pan.hisystem.pojo.User;
import com.pan.hisystem.service.IOutpatientsService;
import com.pan.hisystem.service.IRegistrationService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author qingyang
 * @since 2022-03-13
 */
@Service
public class RegistrationServiceImpl extends ServiceImpl<RegistrationMapper, Registration> implements IRegistrationService {

    @Autowired
    private RegistrationMapper registrationMapper;
    @Autowired
    private IOutpatientsService outpatientsService;

    /**
     * 根据卡号获取挂号记录
     * @param mid
     * @return
     */
    @Override
    public List<Registration> getRecordByMid(String mid) {
        User user=(User)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        List<Registration> registrationList=registrationMapper.getRecordByMid(mid);
        for (Registration registration : registrationList) {
            registration.getUser().setRoles(user.getRoles());
        }
        if(!registrationList.isEmpty()){
            return registrationList;
        }
        return null;
    }

    /**
     * 添加挂号和就诊记录
     * @param registration
     * @param id
     * @return
     */
    @Override
    @Transactional
    public RespBean addRegistrationAndOutPatient(Registration registration, Integer id) {
        Registration registration1=registrationMapper.selectOne(new QueryWrapper<Registration>()
                .eq("mid",registration.getMid())
                .eq("uid",registration.getUid())
                .eq("back_status",false)//未退号且未就诊
                .eq("enabled",false));
        if(registration1!=null){
            return RespBean.error("该患者有挂号未就诊!");
        }
        //生成挂号单的同时生成就诊单，一个患者对一个挂号单对一个就诊单
        if(registrationMapper.insert(registration)==1){
            Outpatients outpatients=new Outpatients();
            outpatients.setMid(registration.getMid());
            outpatients.setUid(registration.getUid());
            outpatients.setRid(registration.getId());
            outpatients.setEnabled(false);
            if(outpatientsService.save(outpatients)){
                return RespBean.success("挂号成功!");
            }
        }
        return RespBean.error("挂号失败!");
    }
}
